package functions.ems_base_data;

import java.util.ArrayList;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.LoggerFactory;

import com.beans.CategoryBean;
import com.beans.SubCategory;
import com.crc.mam.BaseCase;
import coms.AutoException;
import coms.Constants;
import coms.process.LoginTest;
import frame.HttpHelper;



/**
 * 
 * @author CHENHAILIAN6
 * 业务大类
 */
public class Category extends BaseCase{
	private org.slf4j.Logger logger = LoggerFactory.getLogger(Category.class);
	String catagoryId;
	String catagoryName;
	ArrayList<CategoryBean> catagories ;
	ArrayList<SubCategory> subCategories;
	String result;
	boolean isPassed = false;
	String menuCategoryCode;// 差旅费事前申请 不同的数字表示不同的菜单 4001表示借还款
	String menuCategoryName ;
	String subCategoryCode ;
	ArrayList<CategoryBean> allCategories;

	
	public ArrayList<SubCategory> getSubCategories() {
    return subCategories;
  }

  public void setSubCategories(ArrayList<SubCategory> subCategories) {
    this.subCategories = subCategories;
  }

  public ArrayList<CategoryBean> getAllCategories() {
		return allCategories;
	}

	public void setAllCategories(ArrayList<CategoryBean> allCategories) {
		this.allCategories = allCategories;
	}

	/**
	 * 通过categorycode查询
	 * @param categorycode
	 * findCategoryByCategoryCodeUrl="/ems-base-data/category/findCategoryByCategoryCode"
	 */
	public void findCategoryByCategoryCode(String categorycode) {
		String url =  Constants.FIND_CATEGORY_BY_CATEGORY_CODE_URL;
	   	try {
	   		 if(categorycode == null || categorycode == "") {
	   			
	   		 }
	   		  url = url+"?categoryCode="+categorycode;
				result = HttpHelper.post("", url);
				logger.info("findCategoryByCategoryCode --- " + result);
				status = HttpHelper.isOk;
				if(status) {
				try {
				JSONArray array = new JSONArray(result);
				catagories = new ArrayList<CategoryBean>();
					for(int i=0;i<array.length();i++) {
						JSONObject category = (JSONObject) array.get(i);
						String categoryCode = "";
						String categoryName = "";
						String categorDesc = "";
						String valid = "";
						String parentCode = "";
						String lang = "";
						String fullPath = "";
						String leaf = "";
						String categoryLevel = "";
						try {
							categoryCode = (String) category.get("categoryCode");
						}catch(Exception e) {
							
						}
						try {
							categoryName = (String) category.get("categoryName");
						}catch(Exception e) {
							
						}
						try {
							categorDesc = (String) category.get("categorDesc");
						}catch(Exception e) {
							
						}
						try {
							valid = (String) category.get("valid");
						}catch(Exception e) {
							
						}
						try {
							parentCode = (String) category.get("parentCode");
						}catch(Exception e) {
							
						}
						try {
							lang = (String) category.get("lang");
						}catch(Exception e) {
							
						}
						try {
							fullPath = (String) category.get("fullPath");
						}catch(Exception e) {
							
						}
						try {
							leaf = (String) category.get("leaf");
						}catch(Exception e) {
							
						}
						try {
							categoryLevel = (String) category.get("categoryLevel");
						}catch(Exception e) {
							
						}
						CategoryBean bean = new CategoryBean( categoryCode,  categoryName,  categorDesc,  valid, 
								parentCode, lang,  fullPath,  leaf,  categoryLevel);
						System.out.println(bean.toString());
						catagories.add(bean);
					}
				}catch(JSONException e) {
					e.printStackTrace();
					remark = "JSON解析错误";
				}
			}else {
			  JSONObject object = new JSONObject(result);
			  remark = object.getString("message");
		     }
	   	}catch(Exception e) {
	   		e.printStackTrace(); 
	   		status = false;
	   		remark = "系统异常";
	   	}
	   	
	}
	
	/**
	 * 查询子分类信息
	 * subcategoryUrl="/ems-base-data/category/findSubCategoryByCategoryCode?categoryCode=";
	 */
	public void subcategory(String categoryCode) {
		logger.info("查询子分类信息 ----------------- start ------------");
		//String categoryCode = "3001";
		String url =  Constants.SUB_CATEGORY_URL;
		

		url = url + categoryCode;
		try {
			result = HttpHelper.post("", url);
			logger.info("subcategory --- " + result);
			status = HttpHelper.isOk;
			if(status) {
			try {
				JSONArray array = new JSONArray(result);
				subCategories = new ArrayList<SubCategory>();
				for (int i = 0; i < array.length(); i++) {
					SubCategory sub = new SubCategory();
					JSONObject json = (JSONObject) array.get(i);
					try {
						sub.setSubCategoryCode(json.getString("subCategoryCode"));
					} catch (JSONException e) {
						e.printStackTrace();

					}
					try {
						sub.setSubCategorDesc(json.getString("subCategorDesc"));
					} catch (JSONException e) {
						// e.printStackTrace();
						sub.setSubCategorDesc("");

					}
					try {
						sub.setSubCategoryName(json.getString("subCategoryName"));
					} catch (JSONException e) {
						// sub.setSubCategoryName("");
						e.printStackTrace();

					}
					try {
						sub.setValidity(json.getString("validity"));
					} catch (JSONException e) {
						// e.printStackTrace();
						sub.setValidity("");

					}
					subCategories.add(sub);
				}
			} catch (JSONException e) {
			  e.printStackTrace();
			//  status = false;
			  remark = "JSON解析异常";
			}
			}else {
			  JSONObject array = new JSONObject(result);
			  remark = array.getString("message");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("查询子分类信息 ----------------- end ------------");
	}

	
	public void findAllCategoryList() {
		logger.info("查询所有业务大类信息 ----------------- start ------------");
		//String categoryCode = "3001";
		String url =  Constants.FIND_ALL_CATEGORY_LIST_URL;				
		try {
			result = HttpHelper.post("", url);
			System.out.println("findAllCategoryList --- " + result);
			status = HttpHelper.isOk;
			if(status) {
			try {
				JSONArray array = new JSONArray(result);
				allCategories = new ArrayList<CategoryBean>();
				for(int i=0;i<array.length();i++) {
					String categoryCode = "" ;
				    JSONObject object = (JSONObject) array.get(i);
					try {
						categoryCode = (String) object.get("categoryCode");
					}catch(Exception e) {
						categoryCode = "";
					}
					String categoryName = "" ;
				    object = (JSONObject) array.get(i);
					try {
						categoryName = (String) object.get("categoryName");
					}catch(Exception e) {
						categoryName = "";
					}
					String categorDesc = "" ;
				    object = (JSONObject) array.get(i);
					try {
						categorDesc = (String) object.get("categorDesc");
					}catch(Exception e) {
						categorDesc = "";
					}
					String valid = "" ;
				   object = (JSONObject) array.get(i);
					try {
						valid = (String) object.get("valid");
					}catch(Exception e) {
						valid = "";
					}
					String parentCode = "" ;
				    object = (JSONObject) array.get(i);
					try {
						parentCode = (String) object.get("parentCode");
					}catch(Exception e) {
						parentCode = "";
					}
					String lang = "" ;
				    object = (JSONObject) array.get(i);
					try {
						lang = (String) object.get("lang");
					}catch(Exception e) {
						lang = "";
					}
					String fullPath = "" ;
				    object = (JSONObject) array.get(i);
					try {
						fullPath = (String) object.get("fullPath");
					}catch(Exception e) {
						fullPath = "";
					}
					String leaf = "" ;
				    object = (JSONObject) array.get(i);
					try {
						leaf = (String) object.get("leaf");
					}catch(Exception e) {
						leaf = "";
					}
					String categoryLevel = "" ;
				    object = (JSONObject) array.get(i);
					try {
						categoryLevel = (String) object.get("categoryLevel");
					}catch(Exception e) {
						categoryLevel = "";
					}
					CategoryBean bean = new CategoryBean(categoryCode,categoryName,categorDesc, valid, parentCode,
							lang, fullPath,  leaf, categoryLevel);
					allCategories.add(bean);
				}
			} catch (JSONException e) {
			  e.printStackTrace();
			 // status = false;
			  remark = "JSON解析异常";
			}
			}else {
			  JSONObject array = new JSONObject(result);
			  remark = array.getString("message");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("查询所有业务大类信息 ----------------- end ------------");
	}
	

	public static void main(String[] args) {
		
	}
	
	/**
	 * 通过categoryName查找categoryBean
	 * @param name
	 * @return
	 */
	public CategoryBean getCategoryByName(String name) {
		CategoryBean bean = null;
		if(allCategories == null) {
			findAllCategoryList();
		}
		for(CategoryBean category : allCategories) {
			String categoryName = category.getCategoryName();
			if(categoryName.trim().equals(name.trim())) {
				bean = category;
				logger.info(bean.toString());
				break;
			}
		}		
		if(bean == null) {
			try {
				throw new AutoException("------------没有通过大类名称找到对应的大类-------");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bean;
	}
	
	/**
	 * 通过中文路径找到最下层的category
	 * @param path 如:"付款申请->保证金退款->其他保证金退款"
	 * @return
	 */
	public CategoryBean getCategoryByFullPath(String path) {
		CategoryBean bean = null;
		if(allCategories == null) {
			findAllCategoryList();
		}
		String[] paths = path.split("->");
		if(paths.length == 1) {
			bean = getCategoryByName(path);
		}else if(paths.length >1) {
			bean = getCategoryByName(paths[0]);
			for(int j = 1;j<paths.length;j++) {
				for(CategoryBean category : allCategories) {
				
					String categoryName = category.getCategoryName();
					String parentCode = category.getParentCode();
					if(categoryName.trim().equals(paths[j].trim()) && parentCode.equals(bean.getCategoryCode()) ) {
						bean = category;
						break;
					}
				}
			}	
		}
			
		if(bean == null) {
			try {
				throw new Exception("------------没有通过大类名称找到对应的大类-------");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return bean;
	}
	
	public ArrayList<CategoryBean> buildCategoryTree(){
	  ArrayList<CategoryBean> categories = new ArrayList<CategoryBean>();
	  String url =  Constants.FIND_ALL_CATEGORY_LIST_URL;              
      try {
          result = HttpHelper.post("", url);
          logger.info("buildCategoryTree ----" + result);
          status = HttpHelper.isOk;
          if(status) {
            try {
                JSONArray array = new JSONArray(result);
                if(array.length() <1) {
                  logger.error("buildCategoryTree 返回数据为空" );
                }else {
                  for(int i=0;i<array.length();i++) {
                    CategoryBean temp = (CategoryBean) array.get(i);
                    categories.add(temp);
                    boolean hasChilden = true;
                    while(hasChilden) {
                  
                    }
                  }
                }
            }catch(JSONException e) {
             
            }
          }else {
            throw new AutoException("buildCategoryTree 失败");
          }
      }catch(Exception e) {
        
      }
	  return categories;
	}
    
	

}
